//轮询
import {
	mapState
} from 'vuex';
export default {
	data() {
		return {
			networkStatus: 1
		}
	},
	computed: {
		...mapState(['websocketConncted', 'csId', 'classState'])
	},
	destroyed() {

	},
	onLoad() {
		uni.onNetworkStatusChange(this.onNetworkStatusChange);
	},
	onUnload() {
		uni.offNetworkStatusChange(this.onNetworkStatusChange);
	},
	watch: {
		websocketConncted(newVal, oldVal) {
			console.log('这里')
			if (newVal) {
				this.sendPc({
					fun: 'minProjectLogin',
					data: 1,
					time: new Date().getTime()
				}).then(da => {
					console.log('发送信息成功', da)
				});
			}
		}
	},
	onShow() {
		/* 判断websocket 是否需要重连 */
		console.log('打开页面了', this.classState, this.networkStatus, this.$mWebsocket.conncted, this.csId);
		console.log('现在的websocket的状态', this.$mWebsocket.socketTask)
		/*socketTask对象的 readyState 属性四种状态：
		   状态值： 
		      0 -> 表示connecting, 正在连接，连接未完成
		      1 -> 表示opening， 已连接，可以发送和接受消息
		      2 -> 表示closing，正在关闭，还未完成
		      3 -> 表示closed，已关闭
		*/
		this.reWebsocket();
		this.$refs.testListMod && this.$refs.testListMod.mescroll.resetUpScroll();

	},
	methods: {
		sendPc(sendMsg) {
			console.log('sendMsg', sendMsg)
			return this.$postAction(this.$api.sendPc, {
				...sendMsg,
				csId: this.csId,
				time: new Date().getTime()
			})
		},
		//显示菜单
		showMenuMod() {
			this.$refs.menuMod.show();
		},
		reWebsocket() {
			if (this.classState == 'starting' && this.csId && !this.PCConncted) {
				console.log('开始重连websocket')
				if (this.$mWebsocket.socketTask.readyState == 2) {
					setTimeout(() => {
						//重连的时候需要保证还在上课状态
						this.reWebsocket();
					}, 500)
				} else if (this.$mWebsocket.socketTask.readyState == 3) {
					this.$mWebsocket.initWebsocket();
				} else {
					this.sendPc({
						fun: 'minProjectLogin',
						data: 1,
						time: new Date().getTime()
					})
				}
			}
		},
		onNetworkStatusChange(res) {
			console.log('网络的状态', res.isConnected)
			if (res.isConnected) {
				// 当网络连接后的逻辑  
				if (this.classState == 'starting' && this.csId) {
					if (!this.$mWebsocket.conncted) {
						console.log('开始重连websocket')
						this.$mWebsocket.initWebsocket();
					} else {
						this.sendPc({
							fun: 'minProjectLogin',
							data: 1,
							time: new Date().getTime()
						})
					}
				}
			} else {
				// 当网络断开后的逻辑  
				uni.showToast({
					title: "网络已断开",
					icon: 'none'
				});
			}
		}
	},
}